package com.fjwt.gz.task.fans;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.CS;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.entity.FansUserEntity;
import com.fjwt.gz.service.impl.FansUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 小程序注销
 */

@Slf4j
@Component
public class FanUserLogoutTask {

    @Autowired
    private FansUserService fansUserService;

    private static final int LOGOUT_DAYS = 30;

//    @Scheduled(cron = "${cron.FanUserLogoutTask}")
    @Transactional
    public void start() {
        log.info("小程序用户注销功能启动:{}", DateUtil.now());
        // 获取 注销中 且type为微信小程序的 用户
        LambdaQueryWrapper<FansUserEntity> gw = FansUserEntity.gw();
        gw.le(FansUserEntity::getLogoutTime, DateUtil.offsetDay(DateUtil.parse(DateUtil.today()), -LOGOUT_DAYS));
        gw.eq(FansUserEntity::getState, 1);
        gw.eq(FansUserEntity::getType, 1);
        List<FansUserEntity> list = fansUserService.list(gw);
        log.info("小程序用户状态为注销中 且 注销时间在当前时间减30天 的数据：{}", JSON.toJSONString(list));

        if (CollUtil.isEmpty(list)) {
            return;
        }

        boolean flag = this.fansUserService.lambdaUpdate()
                .set(FansUserEntity::getState, 2)
                .eq(FansUserEntity::getState, 1)
                .eq(FansUserEntity::getType, 1)
                .le(FansUserEntity::getLogoutTime, DateUtil.offsetDay(DateUtil.parse(DateUtil.today()), -LOGOUT_DAYS))
                .update();
        log.info("执行修改操作后的返回值：{}", flag);

        this.delRedisKey(list, flag);

        log.info("小程序用户注销功能结束:{}", DateUtil.now());
    }

    /**
     * 清除相应的缓存
     */
    private void delRedisKey(List<FansUserEntity> list, boolean flag) {
        if (flag) {
            // 清除token
            try {
                list.parallelStream()
                        .forEach(item -> {
                            RedisUtil.del(
                                    CS.getCacheKeyToken(CS.SYS_ROLE_TYPE.MCH, item.getFansId(), String.valueOf(item.getFansUserId())),
                                    CS.getCacheKeyTokenList(CS.SYS_ROLE_TYPE.MCH, item.getFansId())
                            );
                        });
            } catch (Exception e) {
                throw new BizException("缓存token操作异常！");
            }
        }
    }

}
